<!-- 角色编辑弹窗 -->
<template>
  <div>
    <el-drawer :visible="drawerEditBoolen"
               size="50%"
               :before-close="handleClose"
               ref="drawer">
      <template v-slot:title>
        <span class="hLabel">{{ isUpdate ? '修改分类' : '添加分类' }}</span>
      </template>
      <div class="ele-body">
        <el-card shadow="never">
          <div class="flex-column-between height83">

            <el-form ref="form"
                     :model="form"
                     :rules="rules"
                     label-width="100px">
              <el-form-item label="跳转类型:"
                            prop="type">
                <el-radio-group v-model="form.type"
                                style="min-width: 700px;">
                  <el-radio :label="1"
                            :disabled="isUpdate?form.type==3?true:false:false"
                            :value="1">搭子</el-radio>
                  <!-- <el-radio :label="2"
                            :value="2">圈子 </el-radio> -->
                  <el-radio :label="3"
                            :disabled="isUpdate?form.type==3?false:true:false"
                            :value="3">服务</el-radio>
                  <!-- <el-radio :label="4"
                            :value="4">社交</el-radio>
                  <el-radio :label="5"
                            :value="5">关注</el-radio>
                  <el-radio :label="6"
                            :value="6">社群</el-radio> -->

                </el-radio-group>

              </el-form-item>
              <el-form-item label="菜单类型:"
                            prop="type">
                <el-radio-group v-model="pidType"
                                style="min-width: 700px;">
                  <el-radio :label="1"
                            :disabled="isUpdate?true:false"
                            :value="1">一级标题</el-radio>
                  <el-radio :label="2"
                            :disabled="isUpdate?true:false"
                            :value="2">二级标题</el-radio>

                </el-radio-group>

              </el-form-item>
              <el-form-item label="分类名称:"
                            prop="name">
                <el-input clearable
                          :maxlength="100"
                          v-model="form.name"
                          placeholder="请输入分类名称">
                </el-input>
              </el-form-item>
              <el-form-item v-if="pidType==1&&form.type==1"
                            label="标签选择:"
                            prop="type_css">
                <span slot="label">
                  背景样式

                </span>
                <el-radio-group v-model="form.type_css"
                                @input="changeStyle">
                  <el-radio label="1">旅游</el-radio>
                  <el-radio label="2">唱歌</el-radio>
                  <el-radio label="3">约饭</el-radio>
                  <el-radio label="4">游戏</el-radio>
                  <el-radio label="5">交友</el-radio>
                  <el-radio label="6">剧本</el-radio>
                  <el-radio label="7">自定义</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="pidType==1&&form.type==1"
                            label="标签样式:"
                            prop="style">
                <img v-if="!isCustom"
                     :src="backgroundStyle"
                     alt=""
                     class="backgroundImg">

                <div v-else>
                  <el-upload action="#"
                             :on-exceed="exceedFn"
                             list-type="picture-card"
                             :file-list="fileListStyle"
                             :limit="1"
                             :on-change="
                    (files, fileListStyle) => handleFileChange(files,'label_icon')
                  "
                             :auto-upload="false">
                    <i slot="default"
                       class="el-icon-plus"></i>
                    <div slot="file"
                         slot-scope="{ file }">
                      <img class="el-upload-list__item-thumbnail"
                           :src="file.url"
                           alt="" />
                      <span class="el-upload-list__item-actions">
                        <!-- <span class="el-upload-list__item-preview"
                            @click="handlePictureCardPreview()">
                        <i class="el-icon-zoom-in"></i>
                      </span> -->
                        <span class="el-upload-list__item-delete"
                              @click="handleDownload(file)">
                          <i class="el-icon-download"></i>
                        </span>
                        <span class="el-upload-list__item-delete"
                              @click="handleRemove_label(file)">
                          <i class="el-icon-delete"></i>
                        </span>
                      </span>
                    </div>
                  </el-upload>
                  <span v-if="form.type_css==7"
                        style="color: red;"> 建议上传尺寸为61*26px的图片</span>
                </div>

              </el-form-item>

              <el-form-item label="一级标题:"
                            prop="pid"
                            v-if="pidType!=1">

                <el-select v-model="form.pid"
                           @change="changePidFn"
                           placeholder="请选择">
                  <el-option v-for="item in optionsArr"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                  </el-option>
                </el-select>
                <!-- <ele-tree-select clearable
                                 v-model="form.pid"
                                 :data="menuList"
                                 label-key="name"
                                 value-key="id"
                                 default-expand-all
                                 placeholder="请选择一级标题" /> -->
              </el-form-item>

              <el-form-item label="排序值:"
                            prop="sort">
                <span slot="label">
                  排序值
                  <el-tooltip placement="top">
                    <div slot="content">
                      用于前端展示排序， 值越小排在前面
                    </div>
                    <i class="el-icon-question" />
                  </el-tooltip>
                </span>
                <el-input clearable
                          type="number"
                          step="1"
                          v-model="form.sort"
                          placeholder="请输入排序值" />
              </el-form-item>

              <!-- 提交图片 -->
              <el-form-item v-if="pidType!=1"
                            label="上传图片:"
                            prop="icon">
                <el-upload action="#"
                           :on-exceed="exceedFn"
                           list-type="picture-card"
                           :file-list="fileList"
                           :limit="1"
                           :on-change="
                    (files, fileList) => handleFileChange(files, 'icon')
                  "
                           :auto-upload="false">
                  <i slot="default"
                     class="el-icon-plus"></i>
                  <div slot="file"
                       slot-scope="{ file }">
                    <img class="el-upload-list__item-thumbnail"
                         :src="file.url"
                         alt="" />
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview"
                            @click="handlePictureCardPreview()">
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span class="el-upload-list__item-delete"
                            @click="handleDownload(file)">
                        <i class="el-icon-download"></i>
                      </span>
                      <span class="el-upload-list__item-delete"
                            @click="handleRemove(file)">
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
                <span style="color: red;">建议尺寸大小为152*152px</span>
              </el-form-item>

            </el-form>
            <div class="drawer__footer">
              <el-button round
                         type="plain"
                         @click="handleClose"
                         size="medium">返回</el-button>
              <el-button type="primary"
                         round
                         :loading="loading"
                         size="medium"
                         @click="save">确定</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </el-drawer>
    <!-- 图片预览 -->
    <el-image-viewer v-if="viewerVisible"
                     style="z-index: 9999"
                     :on-close="closeViewer"
                     :url-list="imgViewArr" />
  </div>
</template>

<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';

// import {
//   userOssSignature,
//   qnyOssSignature
// } from '@/api/creatCenter/material';
// import { storageConfigDetail } from '@/api/storageInfo/index';

// import axios from 'axios';
// import {
//   siteCategoriesInsert,
//   siteCategoriesList,
//   siteCategoriesModify,
//   siteCategoriesDetail
// } from '@/api/serviceManagement/categoriesList';
import { upload } from '@/api/saveImg/index'
import { editClassify, addClassify } from '@/api/classifyList/index'
export default {
  name: 'pictureEdit',
  components: { ElImageViewer },
  props: {
    drawerEditBoolen: {
      type: Boolean,
      default: false
    },
    // 修改回显的数据
    data: Object,
    // 全部菜单数据
    menuList: Array,
    // 上级菜单id
    parentId: Number,
  },
  data () {
    const categoryImage = (rule, value, callback) => {
      console.log(this.form.icon);
      if (!this.form.icon) {
        callback(new Error('请上传图片'));
      } else {
        callback();
      }
    };
    const DEFAULT_FORM = {
      // 分类名称
      name: '',
      //   分类图片
      icon: '',
      // 排序号
      sort: '',
      pid: '',
      type: 1,
      label_icon: '',
      type_css: ''

    };
    return {
      pidType: 1,
      storageMode: 2,

      imageUrl: '',
      imageUrllabel: '',
      imgViewArr: [],
      viewerVisible: false,
      // 表单数据
      form: { ...DEFAULT_FORM },

      dialogImageUrl: '',
      fileList: [],
      dialogVisible: false,
      // 表单验证规则
      rules: {
        name: [
          {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          }
        ],


        sort: [
          {
            required: true,
            message: '请输入排序值',
            trigger: 'blur'
          }
        ],

        type_css: [
          {
            required: true,
            message: '请输入背景样式',
            trigger: 'blur'
          }
        ],
        pid: [
          {
            required: true,
            message: '请选择一级标题名字',
            trigger: 'blur'
          }
        ],
        // 站点 图片上传
        icon: [
          { required: true, validator: categoryImage, trigger: 'change' }
        ]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      showChoose: false,
      optionsArr: [],
      backgroundStyleArr: [
        window.location.origin + '/images/第一行所有图标/组合 784.png',
        window.location.origin + '/images/第一行所有图标/组合 785.png',
        window.location.origin + '/images/第一行所有图标/组合 786.png',
        window.location.origin + '/images/第一行所有图标/组合 788.png',
        window.location.origin + '/images/第一行所有图标/组合 789.png',
        window.location.origin + '/images/第一行所有图标/组合 759.png',

        // 'https://dazi.weijuyunke.cn/images/第一行所有图标/组合 784.png',
        // 'https://dazi.weijuyunke.cn/images/第一行所有图标/组合 785.png',
        // 'https://dazi.weijuyunke.cn/images/第一行所有图标/组合 786.png',
        // 'https://dazi.weijuyunke.cn/images/第一行所有图标/组合 788.png',
        // 'https://dazi.weijuyunke.cn/images/第一行所有图标/组合 789.png',
        // 'https://dazi.weijuyunke.cn/images/第一行所有图标/组合 759.png'

      ],
      backgroundStyle: '',
      isCustom: false,
      fileListStyle: [],
      imageUrlStyle: '',
      // eslint-disable-next-line vue/no-dupe-keys
      fileList: []

    };
  },
  activated () {

  },
  methods: {
    changePidFn (e) {
      console.log(e)
      this.form.pid = e
    },
    changeStyle (e) {
      console.log(e)
      //  样式类型
      this.form.type_css = e
      if (e == 7) {
        this.isCustom = true
        if (!this.isUpdate) {
          this.fileListStyle = [];
          this.imageUrlStyle = '';
        } else {
          this.fileListStyle = [];
          this.imageUrlStyle = '';
          this.form.label_icon = ''
        }

      } else {
        this.isCustom = false
      }
      if (!(e == 7)) {
        this.backgroundStyle = this.backgroundStyleArr[e - 1]
        this.form.label_icon = this.backgroundStyleArr[e - 1]
        console.log(this.backgroundStyle)
      }
    },
    // 获取存储配置
    // async storageConfig () {
    //   const res = await storageConfigDetail();

    //   // console.log(res.storageMode);

    //   this.storageMode = res?.storageMode;
    // },
    // 关闭查看器
    closeViewer () {
      this.viewerVisible = false;
    },
    // 下载图片
    handleDownload (file) {
      window.open(file.url);
    },
    // 删除图片
    handleRemove () {
      this.fileList = [];
      this.imageUrl = '';
      this.form.icon = this.imageUrl;
    },
    handleRemove_label () {
      this.fileListStyle = [];
      this.imageUrlStyle = '';
      this.form.label_icon = ''
    },
    //  图片上传个数超过限制
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
    },
    handlePictureCardPreview () {
      const imgStr = this.imageUrl;
      console.log(imgStr);
      if (imgStr.length) {
        if (imgStr.includes(',')) {
          console.log('字符串中包含逗号');
          // 包含的进行slice(',') 分割

          this.imgViewArr = imgStr.split(',').map((item) => item.trim());
        } else {
          console.log('字符串中不包含逗号');
          this.imgViewArr = imgStr.split();
        }

        this.viewerVisible = true;
      } else {
        this.$message({
          message: '没有上传图片无法进行预览',
          type: 'warning'
        });
      }
    },
    // 关闭抽屉
    handleClose () {
      console.log('查看详情');
      this.$emit('update:drawerEditBoolen', false);
    },
    async handleFileChange (file, name) {

      this.aliFn(file, name)
    },
    // 阿里云
    async aliFn (file, name) {
      this.loading = true;

      let files = file.raw;

      console.log(files)
      // 构建请求参数
      let params = new FormData();
      console.log(params);

      //   params.append('signature', '132321313');
      params.append('file', files);
      console.log(params);

      //   let config = {
      //     headers: {
      //       'Access-Control-Allow-Origin': '*',
      //       'x-oss-callback-Authorization': getToken()
      //     }
      //   };

      const res = await upload(params);
      //   let result = await axios.post(res.host, param, config);
      //   let url = res.host + '/' + date + suffix;
      console.log(res);
      if (res.code == 0) {
        if (name == 'label_icon') {
          this.form.label_icon = res.data.url
          this.loading = false;
        } else {
          this.form.icon = res.data.url
          this.loading = false;
        }
      }
      //   this.form.categoryImages = url;
      //   this.imageUrl = url;
      //   this.loading = false;
    },

    /* 保存编辑 */
    save () {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return false;
        }
        // if (this.isUpdate) {
        //   this.form.img = this.imageUrl;
        // }

        const data = {
          ...this.form
        };
        console.log(data);
        if (this.isUpdate) {
          if (this.data.pid == 0) {
            data.id = this.parentId
          } else {
            data.id = this.data.id

          }
        }

        this.loading = true;

        const saveOrUpdate = this.isUpdate
          ? editClassify
          : addClassify;
        saveOrUpdate(data)
          .then((msg) => {
            console.log(msg);
            this.loading = false;
            this.$message.success(msg.message);

            this.handleClose();
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    }
    /* 更新visible */
  },
  watch: {
    drawerEditBoolen (visible) {
      this.$nextTick(() => {
        if (visible) {
          console.log(this.data);
          if (this.data) {

            if (this.data.pid == 0) {
              this.$util.assignObject(this.form, {
                ...this.data,
                pid: this.data.pid === 0 ? '' : this.data.pid ?? ''
              });
              this.backgroundStyle = this.backgroundStyleArr[Number(this.form.type_css) - 1]
              this.pidType = 1
            } else {
              this.$util.assignObject(this.form, {
                ...this.data,

              });
              this.pidType = 2
            }
            console.log('this.parentId', this.data.pid)

            console.log(this.menuList)
            this.optionsArr = this.menuList.map((item) => {
              return {
                value: item.id,
                label: item.name

              }
            })
            // this.form.id = this.parentId
            if (this.form.icon) {
              this.imageUrl = this.form.icon
              let markIndex = this.form.icon.lastIndexOf('.');
              let suffix = this.form.icon.substring(markIndex);
              if (!this.fileList.length) {
                this.fileList.push({
                  name: suffix,
                  url: this.form.icon
                });
              } else {
                this.fileList = [
                  {
                    name: suffix,
                    url: this.form.icon
                  }
                ];
              }
            } else if (this.form.label_icon) {
              this.isCustom = true
              this.imageUrlStyle = this.form.label_icon
              let markIndex = this.form.label_icon.lastIndexOf('.');
              let suffix = this.form.label_icon.substring(markIndex);

              if (!this.fileListStyle.length) {
                this.fileListStyle.push({
                  name: suffix,
                  url: this.form.label_icon
                });
              } else {
                this.fileListStyle = [
                  {
                    name: suffix,
                    url: this.form.label_icon
                  }
                ];
              }
            } else {
              this.fileList = [];
              this.fileListStyle = []
            }
            this.isUpdate = true;
          } else {
            this.form.pid = '';
            this.isUpdate = false;
            this.pidType = 1

            this.backgroundStyle = ''
            this.form.label_icon = ''

          }
        } else {
          this.form.pid = 0;
          this.$nextTick(() => {
            this.$refs['form'].resetFields();
            console.log(this.form);
          });
          this.fileList = [];
          this.fileListStyle = []

        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
::v-deep .el-upload-list__item {
  transition: none !important;
  -webkit-transition: nonne !important;
}
::v-deep .el-upload-list__item-name {
  transition: none !important;
  -webkit-transition: nonne !important;
}
/*隐藏input（type=number)右边的小箭头*/
/deep/.delInput input::-webkit-outer-spin-button,
/deep/.delInput input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/.delInput input[type='number'] {
  -moz-appearance: textfield;
}
.foodsDiv div {
  margin-left: 20px;
  margin-top: 10px;
}
.height83 {
  height: 83vh;
}
.hLabel {
  margin: 10px 0 20px;
  font-weight: 700;
  &::before {
    content: '';
    display: inline-block;
    vertical-align: top;

    margin-right: 5px;
    height: 23px;
    width: 6px;
    background-color: #1e6ceb;
  }
}
.drawer__footer {
  display: flex;
  justify-content: flex-start;
  margin-left: 15px;
}
</style>
